<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\UserBankcard;
use App\Models\UserBill;
use App\Models\UserExtract;
use App\Models\UserSign;
use App\Services\TimeService;
use Carbon\Carbon;
use Carbon\Traits\Timestamp;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Throwable;
use Tymon\JWTAuth\Payload;

use function Spatie\Ignition\ErrorPage\config;

class UserController extends BaseController
{

    /**
     * 用户银行账户列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-19
     * @param Request $request
     * @return void
     */
    public function userBankList(Request $request)
    {
        return success(UserBankcard::where('user_id', userId())->select('id', 'account_bank', 'account_name', 'card_number')->orderBy('id', 'desc')->get());
    }


    /**
     * 添加银行卡
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-19
     * @param Request $request
     * @return void
     */
    public function createUserBank(Request $request)
    {
        $rules = [
            'account_name' => ['required'],
            'card_number' => ['required'],
            'account_bank' => ['required'],
        ];

        $message = [
            'account_name.required' => '请输入账户名',
            'card_number.required' => '请输入账户号',
            'account_bank.required' => '请输入开户行',
        ];

        $payload = $request->only('account_name', 'card_number', 'account_bank');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(UserBankcard::create([
            'user_id' => userId(),
            'account_bank' => $payload['account_bank'],
            'account_name' => $payload['account_name'],
            'card_number' => $payload['card_number'],
            'card_type' => 1,
            'is_default' => 1
        ]) ? true : []);
    }


    /**
     * 申请提现
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-19
     * @param Request $request
     * @return void
     */
    public function recordCreate(Request $request)
    {
        $rules = [
            'bank_id' => ['required'],
            'bank_code' => ['required'],
            'extract_price' => ['required'],
        ];

        $message = [
            'bank_id.required' => '请选择银行卡',
            'bank_code.required' => '请输入银行卡账户号',
            'extract_price.required' => '请输入提现金额',
        ];

        $payload = $request->only('bank_id', 'bank_code', 'extract_price');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(UserExtract::create([
            'user_id' => userId(),
            'bank_id' => $payload['bank_id'],
            'extract_type' => 'bank',
            'bank_code' => $payload['bank_code'],
            'extract_price' => $payload['extract_price'],
            'mark' => '提现',
            'status' => '0',
        ]) ? true : []);
    }



    /**
     * 提现记录
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-19
     * @param Request $request
     * @return void
     */
    public function recordList(Request $request)
    {
        return success(UserExtract::getUserExtractList(userId()));
    }


    /**
     * 扣款记录
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-20
     * @param Request $request
     * @return void
     */
    public function debitList(Request $request)
    {
        return success(UserBill::getUserBillList(userId()));
    }

    /**
     * 获取检测打卡页面信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-23
     * @param Request $request
     * @return void
     */
    public function getUserClockInfo(Request $request)
    {
        $user = auth('api')->user();

        return success(['is_perfect' => $user->is_perfect, 'clock' => TimeService::getClockDateByUser($user)]);
    }


    /**
     * 完善信息页
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-23
     * @param Request $request
     * @return void
     */
    public function perfectInformation(Request $request)
    {
        $rules = [
            'sex' => ['required'],
            'birthday' => ['required'],
            'gout_or_not' => ['required'],
            'gout_number' => ['required'],

        ];

        $message = [
            'sex.required' => '请选择性别',
            'birthday.required' => '请选择出生日期',
            'gout_or_not.required' => '请选择痛风症状',
            'gout_number.required' => '请选择痛风发作次数',

        ];

        $payload = $request->only('sex', 'birthday', 'gout_or_not', 'gout_number', 'other_symptoms');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(User::where('id', userId())->update([
            'sex' => $payload['sex'],
            'birthday' => $payload['birthday'],
            'gout_or_not' => $payload['gout_or_not'],
            'gout_number' => $payload['gout_number'],
            'other_symptoms' => $payload['other_symptoms'],
            'is_perfect' => 1,
        ]));
    }

    /**
     * 填写打卡记录
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-24
     * @param Request $request
     * @return void
     */
    public function fillInClockRecord(Request $request)
    {
        $rules = [
            'image' => ['required'],
            'number' => ['required'],
            'sign_time' => ['required'],
        ];

        $message = [
            'image.required' => '请上传照片',
            'number.required' => '请输入尿酸值',
            'sign_time.required' => '请输入检测时间',
        ];

        $payload = $request->only('image', 'number', 'sign_time', 'mark');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $user = auth('api')->user();

        // 判断今天是否打过卡，打过卡提示
        $is_sign = UserSign::where('user_id', $user->id)->whereBetween('created_at', [Carbon::today()->startOfDay(), Carbon::today()->endOfDay()])->count();

        if (!empty($is_sign)) {
            return fail([], '今日已打卡', 500);
        }

        DB::beginTransaction();
        try { // 签到打卡
            $res = UserSign::create([
                'user_id' => $user->id,
                'image' => $payload['image'],
                'number' => $payload['number'],
                'sign_time' => $payload['sign_time'],
                'mark' => $payload['mark'],
                'sign_status' => TimeService::getSignStatus($payload['sign_time'], $user->day_of_week),
            ]);

            // 根据返回的sign_status 判断 如果是过期打卡扣钱
            $status = UserBill::setUserBillBySign($res);

            // 写一个定时任务 每天查询所有用户所有未打卡的用户自动扣钱

            if ($res && $status) {
                DB::commit();
                return success();
            } else {

                DB::rollBack();
                return fail_message('失败');
            }
        } catch (Throwable $e) {
            DB::rollBack();
            return fail([], '打卡失败' . $e->getMessage(), 500);
        }
    }


    /**
     * 打卡日历
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-25
     * @param Request $request
     * @return void
     */
    public function calendarList(Request $request)
    {
        $rules = [
            'datetime' => ['required'],

        ];

        $message = [
            'datetime.required' => '请选择日期',

        ];

        $payload = $request->only('datetime');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(UserSign::getCalendarList($payload['datetime'], user()));
    }

    /**
     * 查看打卡日历
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-26
     * @param Request $request
     * @return void
     */
    public function getCalendarInfo(Request $request)
    {
        $rules = [
            'id' => ['required'],

        ];

        $message = [
            'id.required' => '请选择日期',

        ];

        $payload = $request->only('id');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(UserSign::find($payload['id']));
    }


    /**
     * 查看数据
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-10-26
     * @param Request $request
     * @return void
     */
    public function checkCalendarData(Request $request)
    {
        $rules = [
            'start' => ['required'],
            'end' => ['required'],

        ];

        $message = [
            'start.required' => '请选择开始日期',
            'end.required' => '请选择结束日期',
        ];

        $payload = $request->only('start', 'end');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $user = auth('api')->user();
        return success(['signData' => UserSign::getSignDataByDate($payload, $user->id)]);
    }
}
